package com.mipo.mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBConn{
	private static String URL="jdbc:mysql://120.55.57.60:3306/t_uc_user";
	private static String USER_NAME="jack";
	private static String PASSWORD="lj379183595";
	
	private DBConn(){}

	static{
		try{
			Class.forName("com.mysql.jdbc.Driver");
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection(){
		Connection conn=null;
		try{
			conn=DriverManager.getConnection(URL, USER_NAME, PASSWORD);
		}catch(SQLException e){
			e.printStackTrace();
		}
		return conn;
	}
	
	public static void close(Connection conn){
		try{
			if(conn!=null&&!conn.isClosed()){
				conn.close();
			}
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		Connection conn = getConnection();
		try {
			conn.setAutoCommit(false); // 新连接处于自动提交模式
			PreparedStatement ps = conn.prepareStatement("select * from t_user where id = ?");
			ps.setString(1, "1"); // 下标从1开始
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				System.out.println(rs.getString(1)); // 从1开始
				System.out.println(rs.getString(2));
				System.out.println(rs.getString(3));
			}
		} catch (Exception e) {
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally{
			try {
				conn.commit();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
}